/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.flink.streaming.connectors.pinot.segment.name;

import javax.annotation.Nullable;

import static org.apache.flink.util.Preconditions.checkNotNull;

/**
 * Adapted from {@link org.apache.pinot.core.segment.name.SimpleSegmentNameGenerator}.
 * <p>
 * Simple segment name generator which does not perform time conversion.
 * <p>
 * The segment name is simply joining the following fields with '_' but ignoring all the {@code null}s.
 * <ul>
 *   <li>Table name</li>
 *   <li>Minimum time value</li>
 *   <li>Maximum time value</li>
 *   <li>Segment name postfix</li>
 *   <li>Sequence id</li>
 * </ul>
 */
public class SimpleSegmentNameGenerator implements PinotSinkSegmentNameGenerator {

    private final String tableName;
    private final String segmentNamePostfix;

    public SimpleSegmentNameGenerator(String tableName, String segmentNamePostfix) {
        this.tableName = checkNotNull(tableName);
        this.segmentNamePostfix = checkNotNull(segmentNamePostfix);
    }

    @Override
    public String generateSegmentName(int sequenceId, @Nullable Object minTimeValue, @Nullable Object maxTimeValue) {
        return JOINER
                .join(tableName, minTimeValue, maxTimeValue, segmentNamePostfix, sequenceId >= 0 ? sequenceId : null);
    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder("SimpleSegmentNameGenerator: tableName=").append(tableName);
        if (segmentNamePostfix != null) {
            stringBuilder.append(", segmentNamePostfix=").append(segmentNamePostfix);
        }
        return stringBuilder.toString();
    }
}
